import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import FileSystemModel
import SystemIconProvider

ApplicationWindow {
    id: mainWindow
    width: 1024
    height: 768
    visible: true
    title: "Main"
    minimumWidth: 800
    minimumHeight: 600
    flags: Qt.FramelessWindowHint | Qt.Window
    color: "transparent"


    property string selectedFilePath: ""
    property string selectedDirectory: ""
    property string rightPanelCurrentPath: ""
    property var expandedItems: ({})
    property string selectedTool: "disk"  // 默认选中网盘
    property var domainsList: []  // 公司列表
    property string selectedCompanyId: ""  // 当前选中的公司ID
    property string selectedCompanyName: ""  // 当前选中的公司名称

    // 组件初始化时加载公司列表
    Component.onCompleted: {

        // 同步 disk executeSyncDisks
        commandExecutor.executeSyncDisks()

        loadDomains();
        // 初始化系统托盘
        if (systemTrayManager) {
            // 使用 logo.ico 作为托盘图标（C++ 中会自动转换为 : 前缀）
            systemTrayManager.setTrayToolTip("HiApp - 已登录");
        }
    }
    
    // 处理窗口可见性变化（最小化时隐藏窗口并显示托盘）
    onVisibilityChanged: {
        console.log("窗口可见性变化:", visibility);
        // 当窗口最小化时，隐藏窗口并显示托盘图标
        if (visibility === Window.Minimized) {
            console.log("窗口已最小化，准备显示托盘图标");
            // 延迟隐藏，确保最小化动画完成
            hideTimer.start();
        } else if (visibility === Window.Windowed || visibility === Window.Maximized) {
            // 窗口恢复显示时，确保窗口可见并隐藏托盘图标
            console.log("窗口已恢复，隐藏托盘图标");
            mainWindow.visible = true;
            if (systemTrayManager) {
                systemTrayManager.hideTrayIcon();
            }
        }
    }
    
    // 延迟隐藏定时器，确保最小化动画完成
    Timer {
        id: hideTimer
        interval: 100
        onTriggered: {
            console.log("最小化定时器触发，准备隐藏窗口并显示托盘图标");
            mainWindow.visible = false;
            if (systemTrayManager) {
                console.log("调用 showTrayIcon()");
                systemTrayManager.showTrayIcon();
            } else {
                console.log("警告：systemTrayManager 为空");
            }
        }
    }

    // 加载公司列表
    function loadDomains() {
        domainsList = backendService.getDomains();
        console.log("加载公司列表，数量:", domainsList.length);
        
        // 优先尝试加载保存的选中公司ID
        var savedCompanyId = backendService.loadSelectedCompanyId();
        if (savedCompanyId !== "") {
            // 检查保存的公司ID是否还在当前列表中
            var found = false;
            for (var i = 0; i < domainsList.length; i++) {
                if (domainsList[i].id === savedCompanyId) {
                    selectedCompanyId = savedCompanyId;
                    selectedCompanyName = domainsList[i].name;
                    found = true;
                    console.log("加载保存的选中公司:", selectedCompanyName, "ID:", selectedCompanyId);
                    break;
                }
            }
            
            if (!found) {
                console.log("保存的公司ID不在当前列表中，使用默认选择");
                // 如果保存的公司ID不在列表中，使用第一个
                if (domainsList.length > 0) {
                    selectedCompanyId = domainsList[0].id;
                    selectedCompanyName = domainsList[0].name;
                    console.log("默认选择公司:", selectedCompanyName, "ID:", selectedCompanyId);
                }
            }
        } else {
            // 如果没有保存的公司ID，默认选择第一个
            if (domainsList.length > 0) {
                selectedCompanyId = domainsList[0].id;
                selectedCompanyName = domainsList[0].name;
                console.log("默认选择公司:", selectedCompanyName, "ID:", selectedCompanyId);
            }
        }
        
        // 注意：同步文件夹接口应该在Disk.qml中网盘选择时触发
        // 这里不再直接调用syncFolders，因为需要的是diskid而不是domainid
    }

    // 窗口大小调整区域大小
    property int resizeAreaSize: 8
    property int resizeCornerSize: 16

    // 窗口圆角背景
    Rectangle {
        id: mainContainer
        anchors.fill: parent
        anchors.margins: 0
        color: "#ffffff"
        radius: 8
        border.color: "#d0d0d0"
        border.width: 1
        clip: true

        // 主布局
        RowLayout {
            anchors.fill: parent
            anchors.margins: 2
            spacing: 0

            // 最左侧工具面板栏
            Rectangle {
                Layout.fillHeight: true
                Layout.preferredWidth: 64
                color: "#f5f5f5"
                border.color: "#d0d0d0"
                border.width: 1

                // 窗口拖拽区域
                MouseArea {
                    anchors.fill: parent
                    property point startMousePos
                    property point startWindowPos
                    property point currentMousePos
                    property real deltaX: 0
                    property real deltaY: 0
                    property bool isDragging: false

                    onPressed: {
                        startMousePos = Qt.point(mousePosition.globalX, mousePosition.globalY);
                        deltaX = mousePosition.globalX - mainWindow.x;
                        deltaY = mousePosition.globalY - mainWindow.y;
                        isDragging = true;
                        dragTimer.start();
                    }

                    onReleased: {
                        isDragging = false;
                        dragTimer.stop();
                    }

                    onPositionChanged: {
                        if (pressed) {
                            currentMousePos = Qt.point(mousePosition.globalX, mousePosition.globalY);
                        }
                    }

                    // 定时器用于平滑拖拽，避免卡顿
                    Timer {
                        id: dragTimer
                        interval: 16  // 约60FPS
                        repeat: true
                        running: false
                        
                        onTriggered: {
                            if (parent.isDragging && parent.pressed) {
                                console.log("mousePosition.globalX:", mousePosition.globalX, "mousePosition.globalY:", mousePosition.globalY);
                                console.log("parent.deltaX:", parent.deltaX, "parent.deltaY:", parent.deltaY);
                                // 使用全局鼠标坐标
                                mainWindow.x = mousePosition.globalX - parent.deltaX;
                                console.log("mainWindow.x:", mainWindow.x);
                                mainWindow.y = mousePosition.globalY - parent.deltaY;
                                console.log("mainWindow.y:", mainWindow.y);
                            }
                        }
                    } 
                }

                // 头像
                Rectangle {
                    anchors.top: parent.top
                    anchors.left: parent.left
                    anchors.right: parent.right
                    anchors.margins: 8
                    anchors.topMargin: 16
                    height: 48
                    color: "transparent"
                    clip: true

                    // 圆形头像效果
                    Rectangle {
                        anchors.fill: parent
                        radius: 5
                        color: "transparent"
                        border.color: "#d0d0d0"
                        border.width: 1
                        Image {
                            anchors.centerIn: parent
                            width: 40
                            height: 40
                            source: "qrc:/icons/avatar.png"
                            smooth: true
                            antialiasing: true
                            fillMode: Image.PreserveAspectCrop
                        }
                    }

                    MouseArea {
                        anchors.fill: parent
                        hoverEnabled: true
                        propagateComposedEvents: true
                        onEntered: parent.color = "#f0f0f0"
                        onExited: parent.color = "transparent"
                        onClicked: {
                            console.log("点击头像");
                            // 显示用户菜单弹出层
                            avatarPopover.visible = !avatarPopover.visible;
                        }
                    }
                }

                // 工具栏
                Column {
                    anchors.top: parent.top
                    anchors.topMargin: 80  // 头像下方留出空间
                    anchors.left: parent.left
                    anchors.right: parent.right
                    anchors.margins: 8
                    spacing: 12

                    // 网盘图标
                    Rectangle {
                        width: 48
                        height: 48
                        color: selectedTool === "disk" ? "#e3f2fd" : "transparent"
                        border.color: selectedTool === "disk" ? "#2196f3" : "#d0d0d0"
                        border.width: 1
                        radius: 4

                        Image {
                            anchors.centerIn: parent
                            width: 24
                            height: 24
                            source: selectedTool === "disk" ? "qrc:/icons/disk_active.png" : "qrc:/icons/disk.png"
                            smooth: true
                            antialiasing: true
                        }

                        MouseArea {
                            anchors.fill: parent
                            hoverEnabled: true
                            propagateComposedEvents: true
                            onEntered: {
                                if (selectedTool !== "disk") {
                                    parent.color = "#e3f2fd";
                                }
                            }
                            onExited: {
                                if (selectedTool !== "disk") {
                                    parent.color = "transparent";
                                }
                            }
                            onClicked: {
                                selectedTool = "disk";
                                console.log("点击网盘图标");
                                // TODO: 实现网盘功能
                            }
                        }
                    }

                    // 消息图标
                    Rectangle {
                        width: 48
                        height: 48
                        color: selectedTool === "notice" ? "#e3f2fd" : "transparent"
                        border.color: selectedTool === "notice" ? "#2196f3" : "#d0d0d0"
                        border.width: 1
                        radius: 4

                        Image {
                            anchors.centerIn: parent
                            width: 24
                            height: 24
                            source: selectedTool === "notice" ? "qrc:/icons/notice_active.png" : "qrc:/icons/notice.png"
                            smooth: true
                            antialiasing: true
                        }

                        MouseArea {
                            anchors.fill: parent
                            hoverEnabled: true
                            propagateComposedEvents: true
                            onEntered: {
                                if (selectedTool !== "notice") {
                                    parent.color = "#e3f2fd";
                                }
                            }
                            onExited: {
                                if (selectedTool !== "notice") {
                                    parent.color = "transparent";
                                }
                            }
                            onClicked: {
                                selectedTool = "notice";
                                console.log("点击消息图标");
                                // TODO: 实现消息功能
                            }
                        }
                    }

                    // 通讯录图标 - 已隐藏
                    /*
                    Rectangle {
                        width: 48
                        height: 48
                        color: selectedTool === "contects" ? "#e3f2fd" : "transparent"
                        border.color: selectedTool === "contects" ? "#2196f3" : "#d0d0d0"
                        border.width: 1
                        radius: 4

                        Image {
                            anchors.centerIn: parent
                            width: 24
                            height: 24
                            source: selectedTool === "contects" ? "qrc:/icons/contects_active.png" : "qrc:/icons/contects.png"
                            smooth: true
                            antialiasing: true
                        }

                        MouseArea {
                            anchors.fill: parent
                            hoverEnabled: true
                            propagateComposedEvents: true
                            onEntered: {
                                if (selectedTool !== "contects") {
                                    parent.color = "#e3f2fd";
                                }
                            }
                            onExited: {
                                if (selectedTool !== "contects") {
                                    parent.color = "transparent";
                                }
                            }
                            onClicked: {
                                selectedTool = "contects";
                                console.log("点击通讯录图标");
                                // TODO: 实现通讯录功能
                            }
                        }
                    }
                    */

                    // 工作台图标
                    Rectangle {
                        width: 48
                        height: 48
                        color: selectedTool === "workplace" ? "#e3f2fd" : "transparent"
                        border.color: selectedTool === "workplace" ? "#2196f3" : "#d0d0d0"
                        border.width: 1
                        radius: 4

                        Image {
                            anchors.centerIn: parent
                            width: 24
                            height: 24
                            source: selectedTool === "workplace" ? "qrc:/icons/workplace_active.png" : "qrc:/icons/workplace.png"
                            smooth: true
                            antialiasing: true
                        }

                        MouseArea {
                            anchors.fill: parent
                            hoverEnabled: true
                            propagateComposedEvents: true
                            onEntered: {
                                if (selectedTool !== "workplace") {
                                    parent.color = "#e3f2fd";
                                }
                            }
                            onExited: {
                                if (selectedTool !== "workplace") {
                                    parent.color = "transparent";
                                }
                            }
                            onClicked: {
                                console.log("点击工作台图标，打开浏览器");
                                var accessToken = backendService.getAccessToken();
                                var serverHost = backendService.loadServerHost();
                                if (serverHost === "") {
                                    serverHost = "http://localhost:8888";
                                }
                                var url = serverHost + "/signon/api/open-app?accessToken=" + accessToken;
                                Qt.openUrlExternally(url);
                            }
                        }
                    }
                }

                // 我的公司图标
                Rectangle {
                    width: 48
                    height: 48

                    anchors.bottom: parent.bottom
                    anchors.left: parent.left
                    anchors.right: parent.right
                    anchors.margins: 8
                    anchors.bottomMargin: 16

                    color: selectedTool === "mycompany" ? "#e3f2fd" : "transparent"
                    border.color: selectedTool === "mycompany" ? "#2196f3" : "#d0d0d0"
                    border.width: 1
                    radius: 4

                    Column {
                        anchors.centerIn: parent
                        spacing: 2
                        
                        Image {
                            anchors.horizontalCenter: parent.horizontalCenter
                            width: 24
                            height: 24
                            source: selectedTool === "mycompany" ? "qrc:/icons/mycompany_active.png" : "qrc:/icons/mycompany.png"
                            smooth: true
                            antialiasing: true
                        }
                        
                        Text {
                            anchors.horizontalCenter: parent.horizontalCenter
                            text: selectedCompanyName || "我的公司"
                            font.pixelSize: 10
                            color: selectedTool === "mycompany" ? "#2196f3" : "#666666"
                            font.bold: selectedTool === "mycompany"
                            elide: Text.ElideRight
                            width: Math.min(implicitWidth, 40)
                        }
                    }

                    MouseArea {
                        anchors.fill: parent
                        hoverEnabled: true
                        propagateComposedEvents: true
                        onEntered: {
                            if (selectedTool !== "mycompany") {
                                parent.color = "#e3f2fd";
                            }
                        }
                        onExited: {
                            if (selectedTool !== "mycompany") {
                                parent.color = "transparent";
                            }
                        }
                        onClicked: {
                            selectedTool = "mycompany";
                            console.log("点击我的公司图标");
                            // 显示公司选择弹出层
                            companyPopover.visible = !companyPopover.visible;
                        }
                    }
                }
            }

            // 中间内容区域
            Loader {
                id: contentLoader
                Layout.fillHeight: true
                Layout.fillWidth: true
                source: {
                    switch (selectedTool) {
                    case "notice":
                        return "Notice.qml";
                    case "disk":
                        return "Disk.qml";
                    case "contects":
                        return "Disk.qml";  // 通讯录已隐藏，重定向到网盘
                    case "mycompany":
                        return "Disk.qml";  // 我的公司暂时使用网盘组件
                    default:
                        return "Disk.qml";
                    }
                }
            }
        }
    }

    // 窗口大小调整功能
    // 左上角
    Item {
        id: resizeTopLeft
        anchors.top: parent.top
        anchors.left: parent.left
        width: resizeCornerSize
        height: resizeCornerSize
        z: 1000
        
        MouseArea {
            anchors.fill: parent
            hoverEnabled: true
            cursorShape: Qt.SizeFDiagCursor
            acceptedButtons: Qt.LeftButton
        
            property point startPos
            property int startWidth
            property int startHeight
            property int startX
            property int startY
            
            onPressed: function(mouse) {
                startPos = Qt.point(mousePosition.globalX, mousePosition.globalY)
                startWidth = mainWindow.width
                startHeight = mainWindow.height
                startX = mainWindow.x
                startY = mainWindow.y
            }
            
            onPositionChanged: function(mouse) {
                if (pressed) {
                    var deltaX = mousePosition.globalX - startPos.x
                    var deltaY = mousePosition.globalY - startPos.y
                    var newWidth = Math.max(mainWindow.minimumWidth, startWidth - deltaX)
                    var newHeight = Math.max(mainWindow.minimumHeight, startHeight - deltaY)
                    mainWindow.width = newWidth
                    mainWindow.height = newHeight
                    mainWindow.x = startX + (startWidth - newWidth)
                    mainWindow.y = startY + (startHeight - newHeight)
                }
            }
        }
    }

    // 右上角
    Item {
        id: resizeTopRight
        anchors.top: parent.top
        anchors.right: parent.right
        width: resizeCornerSize
        height: resizeCornerSize
        z: 1000
        
        MouseArea {
            anchors.fill: parent
            hoverEnabled: true
            cursorShape: Qt.SizeBDiagCursor
            acceptedButtons: Qt.LeftButton
        
            property point startPos
            property int startWidth
            property int startHeight
            property int startY
            
            onPressed: function(mouse) {
                startPos = Qt.point(mousePosition.globalX, mousePosition.globalY)
                startWidth = mainWindow.width
                startHeight = mainWindow.height
                startY = mainWindow.y
            }
            
            onPositionChanged: function(mouse) {
                if (pressed) {
                    var deltaX = mousePosition.globalX - startPos.x
                    var deltaY = mousePosition.globalY - startPos.y
                    var newWidth = Math.max(mainWindow.minimumWidth, startWidth + deltaX)
                    var newHeight = Math.max(mainWindow.minimumHeight, startHeight - deltaY)
                    mainWindow.width = newWidth
                    mainWindow.height = newHeight
                    mainWindow.y = startY + (startHeight - newHeight)
                }
            }
        }
    }

    // 左下角
    Item {
        id: resizeBottomLeft
        anchors.bottom: parent.bottom
        anchors.left: parent.left
        width: resizeCornerSize
        height: resizeCornerSize
        z: 1000
        
        MouseArea {
            anchors.fill: parent
            hoverEnabled: true
            cursorShape: Qt.SizeBDiagCursor
            acceptedButtons: Qt.LeftButton
        
            property point startPos
            property int startWidth
            property int startHeight
            property int startX
            
            onPressed: function(mouse) {
                startPos = Qt.point(mousePosition.globalX, mousePosition.globalY)
                startWidth = mainWindow.width
                startHeight = mainWindow.height
                startX = mainWindow.x
            }
            
            onPositionChanged: function(mouse) {
                if (pressed) {
                    var deltaX = mousePosition.globalX - startPos.x
                    var deltaY = mousePosition.globalY - startPos.y
                    var newWidth = Math.max(mainWindow.minimumWidth, startWidth - deltaX)
                    var newHeight = Math.max(mainWindow.minimumHeight, startHeight + deltaY)
                    mainWindow.width = newWidth
                    mainWindow.height = newHeight
                    mainWindow.x = startX + (startWidth - newWidth)
                }
            }
        }
    }

    // 右下角
    Item {
        id: resizeBottomRight
        anchors.bottom: parent.bottom
        anchors.right: parent.right
        width: resizeCornerSize
        height: resizeCornerSize
        z: 1000
        
        MouseArea {
            anchors.fill: parent
            hoverEnabled: true
            cursorShape: Qt.SizeFDiagCursor
            acceptedButtons: Qt.LeftButton
        
            property point startPos
            property int startWidth
            property int startHeight
            
            onPressed: function(mouse) {
                startPos = Qt.point(mousePosition.globalX, mousePosition.globalY)
                startWidth = mainWindow.width
                startHeight = mainWindow.height
            }
            
            onPositionChanged: function(mouse) {
                if (pressed) {
                    var deltaX = mousePosition.globalX - startPos.x
                    var deltaY = mousePosition.globalY - startPos.y
                    mainWindow.width = Math.max(mainWindow.minimumWidth, startWidth + deltaX)
                    mainWindow.height = Math.max(mainWindow.minimumHeight, startHeight + deltaY)
                }
            }
        }
    }

    // 上边缘
    Item {
        id: resizeTop
        anchors.top: parent.top
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.leftMargin: resizeCornerSize
        anchors.rightMargin: resizeCornerSize
        height: resizeAreaSize
        z: 1000
        
        MouseArea {
            anchors.fill: parent
            hoverEnabled: true
            cursorShape: Qt.SizeVerCursor
            acceptedButtons: Qt.LeftButton
        
            property point startPos
            property int startHeight
            property int startY
            
            onPressed: function(mouse) {
                startPos = Qt.point(mousePosition.globalX, mousePosition.globalY)
                startHeight = mainWindow.height
                startY = mainWindow.y
            }
            
            onPositionChanged: function(mouse) {
                if (pressed) {
                    var deltaY = mousePosition.globalY - startPos.y
                    var newHeight = Math.max(mainWindow.minimumHeight, startHeight - deltaY)
                    mainWindow.height = newHeight
                    mainWindow.y = startY + (startHeight - newHeight)
                }
            }
        }
    }

    // 下边缘
    Item {
        id: resizeBottom
        anchors.bottom: parent.bottom
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.leftMargin: resizeCornerSize
        anchors.rightMargin: resizeCornerSize
        height: resizeAreaSize
        z: 1000
        
        MouseArea {
            anchors.fill: parent
            hoverEnabled: true
            cursorShape: Qt.SizeVerCursor
            acceptedButtons: Qt.LeftButton
        
            property point startPos
            property int startHeight
            
            onPressed: function(mouse) {
                startPos = Qt.point(mousePosition.globalX, mousePosition.globalY)
                startHeight = mainWindow.height
            }
            
            onPositionChanged: function(mouse) {
                if (pressed) {
                    var deltaY = mousePosition.globalY - startPos.y
                    mainWindow.height = Math.max(mainWindow.minimumHeight, startHeight + deltaY)
                }
            }
        }
    }

    // 左边缘
    Item {
        id: resizeLeft
        anchors.left: parent.left
        anchors.top: parent.top
        anchors.bottom: parent.bottom
        anchors.topMargin: resizeCornerSize
        anchors.bottomMargin: resizeCornerSize
        width: resizeAreaSize
        z: 1000
        
        MouseArea {
            anchors.fill: parent
            hoverEnabled: true
            cursorShape: Qt.SizeHorCursor
            acceptedButtons: Qt.LeftButton
        
            property point startPos
            property int startWidth
            property int startX
            
            onPressed: function(mouse) {
                startPos = Qt.point(mousePosition.globalX, mousePosition.globalY)
                startWidth = mainWindow.width
                startX = mainWindow.x
            }
            
            onPositionChanged: function(mouse) {
                if (pressed) {
                    var deltaX = mousePosition.globalX - startPos.x
                    var newWidth = Math.max(mainWindow.minimumWidth, startWidth - deltaX)
                    mainWindow.width = newWidth
                    mainWindow.x = startX + (startWidth - newWidth)
                }
            }
        }
    }

    // 右边缘
    Item {
        id: resizeRight
        anchors.right: parent.right
        anchors.top: parent.top
        anchors.bottom: parent.bottom
        anchors.topMargin: resizeCornerSize
        anchors.bottomMargin: resizeCornerSize
        width: resizeAreaSize
        z: 1000
        
        MouseArea {
            anchors.fill: parent
            hoverEnabled: true
            cursorShape: Qt.SizeHorCursor
            acceptedButtons: Qt.LeftButton
        
            property point startPos
            property int startWidth
            
            onPressed: function(mouse) {
                startPos = Qt.point(mousePosition.globalX, mousePosition.globalY)
                startWidth = mainWindow.width
            }
            
            onPositionChanged: function(mouse) {
                if (pressed) {
                    var deltaX = mousePosition.globalX - startPos.x
                    mainWindow.width = Math.max(mainWindow.minimumWidth, startWidth + deltaX)
                }
            }
        }
    }

    // 连接信号

    // 连接系统托盘信号
    Connections {
        target: systemTrayManager
        function onShowWindowRequested() {
            // 双击托盘图标时显示窗口
            mainWindow.visible = true;
            mainWindow.show();
            mainWindow.raise();
            mainWindow.requestActivate();
            // 确保窗口不是最小化状态
            if (mainWindow.visibility === Window.Minimized) {
                mainWindow.showNormal();
            }
            if (systemTrayManager) {
                systemTrayManager.hideTrayIcon();
            }
        }
    }

    Connections {
        target: fileSystemModel
        function onCurrentDirectoryFilesChanged() {
            // 图标视图会自动更新
        }
    }

    // 公司选择弹出层
    Rectangle {
        id: companyPopover
        width: 300
        height: Math.min(400, domainsList.length * 60 + 80)
        color: "#ffffff"
        border.color: "#d0d0d0"
        border.width: 1
        radius: 8
        visible: false
        z: 1000  // 确保在最上层
        
        // 定位在左侧工具面板的右侧
        anchors.left: mainContainer.left
        anchors.leftMargin: 64 + 8  // 左侧面板宽度 + 间距
        anchors.bottom: mainContainer.bottom
        anchors.bottomMargin: 16 + 48 + 8  // 底部边距 + 图标高度 + 间距
        
        // 阴影效果
        Rectangle {
            anchors.fill: parent
            anchors.margins: -2
            color: "transparent"
            border.color: "#e0e0e0"
            border.width: 1
            radius: 10
            z: -1
        }
        
        ColumnLayout {
            anchors.fill: parent
            anchors.margins: 16
            spacing: 8
            
            // 标题栏
            RowLayout {
                Layout.fillWidth: true
                spacing: 8
                
                Text {
                    text: "选择公司"
                    font.pixelSize: 16
                    font.bold: true
                    color: "#333333"
                    Layout.fillWidth: true
                }
                
                // 关闭按钮
                Rectangle {
                    width: 24
                    height: 24
                    radius: 12
                    color: "#f0f0f0"
                    border.color: "#d0d0d0"
                    border.width: 1
                    
                    Text {
                        anchors.centerIn: parent
                        text: "×"
                        font.pixelSize: 14
                        font.bold: true
                        color: "#666666"
                    }
                    
                    MouseArea {
                        anchors.fill: parent
                        onClicked: {
                            companyPopover.visible = false;
                        }
                    }
                }
            }
            
            ScrollView {
                Layout.fillWidth: true
                Layout.fillHeight: true
                Layout.topMargin: 8
                
                ListView {
                    id: companyListView
                    model: domainsList
                    spacing: 4
                    
                    delegate: Rectangle {
                        width: companyListView.width
                        height: 50
                        color: selectedCompanyId === modelData.id ? "#e3f2fd" : "transparent"
                        border.color: selectedCompanyId === modelData.id ? "#2196f3" : "#e0e0e0"
                        border.width: 1
                        radius: 4
                        
                        RowLayout {
                            anchors.fill: parent
                            anchors.margins: 12
                            spacing: 12
                            
                            // 公司图标
                            Rectangle {
                                width: 32
                                height: 32
                                radius: 16
                                color: "#f0f0f0"
                                border.color: "#d0d0d0"
                                border.width: 1
                                
                                Text {
                                    anchors.centerIn: parent
                                    text: modelData.name ? modelData.name.charAt(0) : "?"
                                    font.pixelSize: 14
                                    font.bold: true
                                    color: "#666666"
                                }
                            }
                            
                            // 公司信息
                            ColumnLayout {
                                Layout.fillWidth: true
                                spacing: 2
                                
                                Text {
                                    text: modelData.name || "未知公司"
                                    font.pixelSize: 14
                                    font.bold: true
                                    color: "#333333"
                                    Layout.fillWidth: true
                                    elide: Text.ElideRight
                                }
                                
                                Text {
                                    text: "ID: " + (modelData.id || "")
                                    font.pixelSize: 12
                                    color: "#666666"
                                    Layout.fillWidth: true
                                    elide: Text.ElideRight
                                }
                            }
                            
                            // 选中状态指示器
                            Rectangle {
                                width: 16
                                height: 16
                                radius: 8
                                color: selectedCompanyId === modelData.id ? "#2196f3" : "transparent"
                                border.color: selectedCompanyId === modelData.id ? "#2196f3" : "#d0d0d0"
                                border.width: 1
                                
                                Text {
                                    anchors.centerIn: parent
                                    text: "✓"
                                    color: "white"
                                    font.pixelSize: 10
                                    font.bold: true
                                    visible: selectedCompanyId === modelData.id
                                }
                            }
                        }
                        
                        MouseArea {
                            anchors.fill: parent
                            onClicked: {
                                selectedCompanyId = modelData.id;
                                selectedCompanyName = modelData.name;
                                console.log("选择公司:", selectedCompanyName, "ID:", selectedCompanyId);
                                
                                // 保存选中的公司ID到设置文件
                                backendService.saveSelectedCompanyId(selectedCompanyId);
                                
                                companyPopover.visible = false;
                            }
                        }
                    }
                }
            }
            
        }
    }

    // 头像菜单弹出层
    Rectangle {
        id: avatarPopover
        width: 200
        height: 60
        color: "#ffffff"
        border.color: "#d0d0d0"
        border.width: 1
        radius: 8
        visible: false
        z: 1000  // 确保在最上层
        
        // 定位在左侧工具面板的右侧，头像下方
        anchors.left: mainContainer.left
        anchors.leftMargin: 64 + 8  // 左侧面板宽度 + 间距
        anchors.top: mainContainer.top
        anchors.topMargin: 16 + 48 + 8  // 顶部边距 + 头像高度 + 间距
        
        // 阴影效果
        Rectangle {
            anchors.fill: parent
            anchors.margins: -2
            color: "transparent"
            border.color: "#e0e0e0"
            border.width: 1
            radius: 10
            z: -1
        }
        
        ColumnLayout {
            anchors.fill: parent
            anchors.margins: 8
            spacing: 0
            
            // 退出登录菜单项
            Rectangle {
                Layout.fillWidth: true
                height: 44
                color: exitSystemMouseArea.containsMouse ? "#f0f0f0" : "transparent"
                radius: 4
                
                RowLayout {
                    anchors.fill: parent
                    anchors.margins: 12
                    spacing: 12
                    
                    Text {
                        text: "退出登录"
                        font.pixelSize: 14
                        color: "#333333"
                        Layout.fillWidth: true
                    }
                }
                
                MouseArea {
                    id: exitSystemMouseArea
                    anchors.fill: parent
                    hoverEnabled: true
                    onClicked: {
                        avatarPopover.visible = false;
                        // 显示退出登录确认对话框
                        logoutConfirmDialog.open();
                    }
                }
            }
        }
    }

    // 全局点击区域，用于点击外部关闭弹出层
    MouseArea {
        anchors.fill: parent
        enabled: companyPopover.visible || avatarPopover.visible
        onClicked: {
            companyPopover.visible = false;
            avatarPopover.visible = false;
        }
        z: 999  // 在弹出层下方
    }

    // 退出系统确认对话框（用于窗口关闭）
    Dialog {
        id: closeConfirmDialog
        title: "确认退出系统"
        anchors.centerIn: parent
        width: 350
        modal: true
        
        background: Rectangle {
            color: "#ffffff"
            border.color: "#d0d0d0"
            border.width: 1
            radius: 4
        }
        
        contentItem: ColumnLayout {
            spacing: 20
            anchors.margins: 20

            
            Text {
                text: "确定要退出程序吗？"
                font.pixelSize: 14
                color: "#333333"
                Layout.fillWidth: true
                Layout.alignment: Qt.AlignHCenter
            }
            
            RowLayout {
                Layout.fillWidth: true
                Layout.alignment: Qt.AlignHCenter
                spacing: 10
                
                Button {
                    text: "确定"
                    Layout.preferredWidth: 80
                    onClicked: {
                        closeConfirmDialog.close();
                        Qt.quit();
                    }
                }
                
                Button {
                    text: "取消"
                    Layout.preferredWidth: 80
                    onClicked: {
                        closeConfirmDialog.close();
                    }
                }
            }
        }
    }

    // 退出登录确认对话框（用于头像菜单）
    Dialog {
        id: logoutConfirmDialog
        title: "确认退出登录"
        anchors.centerIn: parent
        width: 350
        modal: true
        
        background: Rectangle {
            color: "#ffffff"
            border.color: "#d0d0d0"
            border.width: 1
            radius: 4
        }
        
        contentItem: ColumnLayout {
            spacing: 20
            anchors.margins: 20

            
            Text {
                text: "确定要退出登录吗？"
                font.pixelSize: 14
                color: "#333333"
                Layout.fillWidth: true
                Layout.alignment: Qt.AlignHCenter
            }
            
            RowLayout {
                Layout.fillWidth: true
                Layout.alignment: Qt.AlignHCenter
                spacing: 10
                
                Button {
                    text: "确定"
                    Layout.preferredWidth: 80
                    onClicked: {
                        logoutConfirmDialog.close();
                        // 执行退出登录
                        backendService.logout();

                        mainWindow.visible = false;
                        // 显示托盘图标
                        if (systemTrayManager) {
                            systemTrayManager.showTrayIcon();
                        }
                    }
                }
                
                Button {
                    text: "取消"
                    Layout.preferredWidth: 80
                    onClicked: {
                        logoutConfirmDialog.close();
                    }
                }
            }
        }
    }

    // 处理窗口关闭事件
    onClosing: function(close) {
        // 阻止默认关闭行为，显示退出系统确认对话框
        close.accepted = false;
        if (!closeConfirmDialog.visible) {
            closeConfirmDialog.open();
        }
    }

}
